package com.cyy.util

import java.awt.Desktop
import java.net.URISyntaxException
import java.io.IOException
import java.util.HashMap
import okhttp3.*
import okhttp3.Headers.Companion.toHeaders
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody.Companion.toRequestBody
import java.net.URI


object HttpClientUtil {
    fun getHttpDataAsUTF_8(url: String, refererUrl: String): String? {
        try {
            val headerMap = HashMap<String, String>()
            headerMap["Referer"] = refererUrl
            val client = OkHttpClient()
            val builder = FormBody.Builder()
            val request = Request.Builder().url(url).headers(headerMap.toHeaders()).build()
            val response = client.newCall(request).execute()
            return response.body?.string()
        } catch (e: Exception) {
            e.printStackTrace()
        }

        return null
    }

    fun getHttpDataByPost(url: String, refererUrl: String, map: Map<String, String>): String? {
        try {
            val client = OkHttpClient()
            val builder = FormBody.Builder()
            map.forEach { (key: String, value: String) ->
                if (value != null) {
                    builder.add(key, value)
                }
            }
            val body = builder.build()
            val headerMap = HashMap<String, String>()
            headerMap["Referer"] = refererUrl
            val request = Request.Builder().url(url).post(body).headers(headerMap.toHeaders()).build()
            val response = client.newCall(request).execute()
            return response.body?.string()
        } catch (e: Exception) {
            e.printStackTrace()
        }

        return null
    }

    fun getHttpDataByPost(url: String, refererUrl: String, string: String): String? {
        return getHttpDataByPost(url, refererUrl, string, "text/x-markdown; charset=utf-8")
    }

    fun getHttpDataByPost(url: String, refererUrl: String, string: String, header: String): String? {
        try {
            val client = OkHttpClient()
            val body = string.toRequestBody(header.toMediaTypeOrNull())
            val headerMap = HashMap<String, String>()
            headerMap["Referer"] = refererUrl
            val request = Request.Builder().url(url).post(body).headers(headerMap.toHeaders()).build()
            val response = client.newCall(request).execute()
            return response.body?.string()
        } catch (e: Exception) {
            e.printStackTrace()
        }

        return null
    }

    fun openBrowseURL(url: String) {
        val desktop = Desktop.getDesktop()
        try {
            desktop.browse(URI(url))
        } catch (e1: Exception) {
            e1.printStackTrace()
        }

    }

    @Throws(IOException::class, URISyntaxException::class)
    fun openBrowseURLThrowsException(url: String) {
        val desktop = Desktop.getDesktop()
        desktop.browse(URI(url))
    }
}